import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
var baseUrl = 'ws://192.168.1.6:80/app/im/singleRoom'
var url = '';
//监听网络变化
const socket = new Vuex.Store({
	state: {
		socketTask: null
	},
	mutations: {
		WEBSOCKET_INIT(state, data) {
			url = baseUrl + "/" + data.uid + "/" + data.token
			state.socketTask = uni.connectSocket({
				url, // url是websocket连接ip
				success() {
					console.log('websocket连接成功', url)
					//开启网络切换监听
					uni.onNetworkStatusChange(function(res) {
						if (res.isConnected) {
							//尝试重连
							state.socketTask = null;
							state.socketTask.close({
								success(res) {
									console.log('关闭成功', res)
									console.log("异常重新连接")
									//尝试重连
									state.socketTask = uni.connectSocket({
										url, // url是websocket连接ip
										success() {
											console.log('websocket连接成功', url)
										}
									})
								},
								fail(err) {
									console.log('关闭失败', err)
								}
							})
						}
					});
				}
			})
			state.socketTask.onOpen((res) => {
				state.socketTask.onMessage(res => {
					console.log('收到服务器内容：' + res.data)
					uni.showTabBarRedDot({
						index: 2
					})
				});
			})
			state.socketTask.onClose(function() {
				//尝试重连
				state.socketTask = null;
				state.socketTask.close({
					success(res) {
						console.log('关闭成功', res)
						console.log("异常重新连接")
						//尝试重连
						state.socketTask = uni.connectSocket({
							url, // url是websocket连接ip
							success() {
								console.log('websocket连接成功', url)
							}
						})
					},
					fail(err) {
						console.log('关闭失败', err)
					}
				})
			})
			state.socketTask.onError(function() {
				//尝试重连
				state.socketTask = null;
				state.socketTask.close({
					success(res) {
						console.log('关闭成功', res)
						console.log("异常重新连接")
						//尝试重连
						state.socketTask = uni.connectSocket({
							url, // url是websocket连接ip
							success() {
								console.log('websocket连接成功', url)
							}
						})
					},
					fail(err) {
						console.log('关闭失败', err)
					}
				})
			})
		},
		WEBSOCKET_SEND(state, data) {
			state.socketTask.send({
				data,
				async success() {
					console.log('消息发送成功')
				},
			})
		},
		CLOSE_SOCKET(state) {
			if (!state.socketTask) return
			state.socketTask.close({
				success(res) {
					console.log('关闭成功', res)
					//尝试重连

				},
				fail(err) {
					console.log('关闭失败', err)
				}
			})
		}
	},
	actions: {
		WEBSOCKET_INIT({
			commit
		}, data) {
			commit('WEBSOCKET_INIT', data)
		},
		WEBSOCKET_SEND({
			commit
		}, data) {
			commit('WEBSOCKET_SEND', data)
		},
		CLOSE_SOCKET({
			commit
		}) {
			commit('CLOSE_SOCKET')
		}
	}
})

export default socket
